import router from './router'
import store from './store'
import Cookie from 'js-cookie'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import { TokenType } from '@/utils/enum'
import { Loading } from 'element-ui';
import Token from './utils/token'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login','/wxWorkLogin','/qrcode-login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  var user_token = Cookie.get(TokenType.USER_TOKEN)
  var user_refreshtoken = Cookie.get(TokenType.USER_REFRESHTOKEN)
  console.log(to.path)

  if(to.path == '/logout') {
    Token.remove();
    sessionStorage.clear();
    store.dispatch('user/fedLogOut')
    return
  }

  if (!user_token) {
    sessionStorage.clear()
    //登录页面无token可以进入
    if (whiteList.indexOf(to.path) >= 0) {
      console.log(to.path + ":无token直接进入")
      next()
      return
    }
    console.log(to)
    Cookie.set('redirect', 'true')
    Cookie.set('redirect_url', to.fullPath)
    //跳转到企业微信登录
    store.dispatch('user/fedLogOut')
    return
  }

  if (user_token) {
    //有token 登录直接跳转到首页
    if (whiteList.indexOf(to.path) >= 0) {
      next({ path: '/' })
      return
    }
    if (store.getters.routes.length === 0) {
      const loadingObj = Loading.service({
        lock: true,
        text: '系统加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      const result = await store.dispatch('user/getInfo')
      if (result) {
        loadingObj.close();
        router.addRoutes(store.getters.routes)
        next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
      }
      return
    }
    next()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
